package com.lanou3g.demo.dao;

import com.lanou3g.demo.db.DBConnector;
import com.lanou3g.demo.db.EntityListHandler;
import com.lanou3g.demo.entity.CategoryEntity;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CategoryDao {


    public static List<CategoryEntity> categoryAll () throws SQLException {
        Connection conn= DBConnector.getInstance().getConnection();
        QueryRunner runner=new QueryRunner();
        String sql="select * from category ";
        List<CategoryEntity> categoryEntityList = runner.query(conn, sql, new EntityListHandler<>(CategoryEntity.class));
        return categoryEntityList;
    }


    public static void addCategory (String cid,String cname) throws SQLException {
        Connection conn=DBConnector.getInstance().getConnection();
        QueryRunner runner=new QueryRunner();
        String sql="insert into category value(?,?)";
        runner.update(conn,sql,cid,cname);
    }

    public static void deleteCategory (String cid) throws SQLException {
        Connection conn=DBConnector.getInstance().getConnection();
        QueryRunner runner=new QueryRunner();
        String sqp="delete from category where cid = ?";
        runner.update(conn,sqp,cid);
    }

    public static void updateCategory (String cid,String cname) throws SQLException {
        Connection conn=DBConnector.getInstance().getConnection();
        QueryRunner runner=new QueryRunner();
        String sqpl="update category set cname = ? where cid = ?";
        runner.update(conn,sqpl,cname,cid);
    }
}
